<script lang="ts" setup>
import { computed, h, onMounted, reactive, ref } from 'vue';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tabs,
  Tag,
} from 'ant-design-vue';

// 租客状态枚举
const TenantStatus = {
  ACTIVE: 'active',
  INACTIVE: 'inactive',
  EXPIRED: 'expired',
} as const;

// 合同状态枚举
const ContractStatus = {
  ACTIVE: 'active',
  EXPIRED: 'expired',
  TERMINATED: 'terminated',
  PENDING: 'pending',
} as const;

// 配置对象
const tenantStatusConfig = {
  [TenantStatus.ACTIVE]: { label: '在租', color: 'green' },
  [TenantStatus.INACTIVE]: { label: '退租', color: 'gray' },
  [TenantStatus.EXPIRED]: { label: '到期', color: 'orange' },
};

const contractStatusConfig = {
  [ContractStatus.ACTIVE]: { label: '生效中', color: 'green' },
  [ContractStatus.EXPIRED]: { label: '已到期', color: 'orange' },
  [ContractStatus.TERMINATED]: { label: '已终止', color: 'red' },
  [ContractStatus.PENDING]: { label: '待生效', color: 'blue' },
};

// 响应式数据
const activeTab = ref('tenants');
const loading = ref(false);
const tenantModalVisible = ref(false);
const contractModalVisible = ref(false);
const selectedTenant = ref<any>(null);
const selectedContract = ref<any>(null);

// 表单引用
const tenantFormRef = ref();
const contractFormRef = ref();

// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
  roomNumber: '',
  status: '',
});

// 合同搜索表单
const contractSearchForm = reactive({
  name: '',
  roomNumber: '',
  status: '',
});

// 租客表单
const tenantForm = reactive({
  name: '',
  phone: '',
  idCard: '',
  email: '',
  emergencyContact: '',
  emergencyPhone: '',
  occupation: '',
  workUnit: '',
  annualIncome: '',
  creditScore: 0,
  remark: '',
});

// 合同表单
const contractForm = reactive({
  tenantId: '',
  roomNumber: '',
  startDate: null,
  endDate: null,
  rent: 0,
  deposit: 0,
  paymentDay: 1,
  remark: '',
});

// 表单验证规则
const tenantRules = {
  name: [{ required: true, message: '请输入租客姓名' }],
  phone: [{ required: true, message: '请输入联系电话' }],
  idCard: [{ required: true, message: '请输入身份证号' }],
};

const contractRules = {
  tenantId: [{ required: true, message: '请选择租客' }],
  roomNumber: [{ required: true, message: '请输入房间号' }],
  startDate: [{ required: true, message: '请选择开始日期' }],
  endDate: [{ required: true, message: '请选择结束日期' }],
  rent: [{ required: true, message: '请输入月租金' }],
};

// 模拟数据
const tenantList = ref<any[]>([
  {
    id: 1,
    name: '张三',
    phone: '13800138001',
    idCard: '110101199001011234',
    email: 'zhangsan@example.com',
    emergencyContact: '李四',
    emergencyPhone: '13800138002',
    status: TenantStatus.ACTIVE,
    roomNumber: '101',
    createTime: '2024-01-01',
    remark: '长期租客',
    occupation: '工程师',
    workUnit: '某科技公司',
    annualIncome: '150000',
    creditScore: 85,
  },
  {
    id: 2,
    name: '王五',
    phone: '13800138003',
    idCard: '110101199002021234',
    email: 'wangwu@example.com',
    emergencyContact: '赵六',
    emergencyPhone: '13800138004',
    status: TenantStatus.ACTIVE,
    roomNumber: '102',
    createTime: '2024-01-15',
    remark: '新租客',
    occupation: '设计师',
    workUnit: '某设计公司',
    annualIncome: '120000',
    creditScore: 78,
  },
]);

const contractList = ref<any[]>([
  {
    id: 1,
    tenantId: 1,
    tenantName: '张三',
    roomNumber: '101',
    startDate: '2024-01-01',
    endDate: '2024-12-31',
    rent: 3000,
    deposit: 6000,
    paymentDay: 1,
    status: ContractStatus.ACTIVE,
    createTime: '2024-01-01',
    remark: '标准合同',
  },
  {
    id: 2,
    tenantId: 2,
    tenantName: '王五',
    roomNumber: '102',
    startDate: '2024-01-15',
    endDate: '2024-12-15',
    rent: 2800,
    deposit: 5600,
    paymentDay: 15,
    status: ContractStatus.ACTIVE,
    createTime: '2024-01-15',
    remark: '优惠合同',
  },
]);

const checkinRecords = ref<any[]>([
  {
    id: 1,
    tenantName: '张三',
    roomNumber: '101',
    checkinDate: '2024-01-01',
    estimatedExpiry: '2024-12-31',
    contractStatus: '生效中',
    remark: '正常入住',
  },
  {
    id: 2,
    tenantName: '王五',
    roomNumber: '102',
    checkinDate: '2024-01-15',
    estimatedExpiry: '2024-12-15',
    contractStatus: '生效中',
    remark: '正常入住',
  },
]);

const tenantHistory = ref<any[]>([
  {
    id: 1,
    tenantName: '张三',
    roomNumber: '101',
    checkinDate: '2024-01-01',
    checkoutDate: null,
    creditRecord: '良好',
    paymentRecord: '按时缴费',
    complaintRecord: '无投诉',
  },
  {
    id: 2,
    tenantName: '王五',
    roomNumber: '102',
    checkinDate: '2024-01-15',
    checkoutDate: null,
    creditRecord: '良好',
    paymentRecord: '按时缴费',
    complaintRecord: '无投诉',
  },
]);

// 计算属性
const filteredTenantList = computed(() => {
  return tenantList.value.filter((tenant) => {
    const nameMatch = !searchForm.name || tenant.name.includes(searchForm.name);
    const phoneMatch =
      !searchForm.phone || tenant.phone.includes(searchForm.phone);
    const roomMatch =
      !searchForm.roomNumber ||
      tenant.roomNumber.includes(searchForm.roomNumber);
    const statusMatch =
      !searchForm.status || tenant.status === searchForm.status;
    return nameMatch && phoneMatch && roomMatch && statusMatch;
  });
});

const filteredContractList = computed(() => {
  return contractList.value.filter((contract) => {
    const nameMatch =
      !contractSearchForm.name ||
      contract.tenantName.includes(contractSearchForm.name);
    const roomMatch =
      !contractSearchForm.roomNumber ||
      contract.roomNumber.includes(contractSearchForm.roomNumber);
    const statusMatch =
      !contractSearchForm.status ||
      contract.status === contractSearchForm.status;
    return nameMatch && roomMatch && statusMatch;
  });
});

// 表格列配置
const tenantColumns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    width: 120,
  },
  {
    title: '联系电话',
    dataIndex: 'phone',
    key: 'phone',
    width: 130,
  },
  {
    title: '身份证号',
    dataIndex: 'idCard',
    key: 'idCard',
    width: 180,
  },
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 100,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ text }: { text: string }) => {
      const config =
        tenantStatusConfig[text as keyof typeof tenantStatusConfig];
      return config
        ? h(Tag, { color: config.color }, () => config.label)
        : text;
    },
  },
  {
    title: '职业',
    dataIndex: 'occupation',
    key: 'occupation',
    width: 120,
  },
  {
    title: '信用评分',
    dataIndex: 'creditScore',
    key: 'creditScore',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 120,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    customRender: ({ record }: { record: any }) => {
      return h(Space, {}, [
        h(
          Button,
          {
            onClick: () => editTenant(record),
            size: 'small',
            type: 'link',
          },
          () => '编辑',
        ),
        h(
          Button,
          {
            onClick: () => viewTenantDetail(record),
            size: 'small',
            type: 'link',
          },
          () => '详情',
        ),
        h(
          Button,
          {
            danger: true,
            onClick: () => deleteTenant(record),
            size: 'small',
            type: 'link',
          },
          () => '删除',
        ),
      ]);
    },
  },
];

const contractColumns = [
  {
    title: '租客姓名',
    dataIndex: 'tenantName',
    key: 'tenantName',
    width: 120,
  },
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 100,
  },
  {
    title: '开始日期',
    dataIndex: 'startDate',
    key: 'startDate',
    width: 120,
  },
  {
    title: '结束日期',
    dataIndex: 'endDate',
    key: 'endDate',
    width: 120,
  },
  {
    title: '月租金',
    dataIndex: 'rent',
    key: 'rent',
    width: 100,
    customRender: ({ text }: { text: number }) => `¥${text}`,
  },
  {
    title: '押金',
    dataIndex: 'deposit',
    key: 'deposit',
    width: 100,
    customRender: ({ text }: { text: number }) => `¥${text}`,
  },
  {
    title: '缴费日',
    dataIndex: 'paymentDay',
    key: 'paymentDay',
    width: 80,
    customRender: ({ text }: { text: number }) => `每月${text}日`,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    customRender: ({ text }: { text: string }) => {
      const config =
        contractStatusConfig[text as keyof typeof contractStatusConfig];
      return config
        ? h(Tag, { color: config.color }, () => config.label)
        : text;
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    customRender: ({ record }: { record: any }) => {
      return h(Space, {}, [
        h(
          Button,
          {
            onClick: () => editContract(record),
            size: 'small',
            type: 'link',
          },
          () => '编辑',
        ),
        h(
          Button,
          {
            onClick: () => viewContractDetail(record),
            size: 'small',
            type: 'link',
          },
          () => '详情',
        ),
        h(
          Button,
          {
            danger: true,
            onClick: () => terminateContract(record),
            size: 'small',
            type: 'link',
          },
          () => '终止',
        ),
      ]);
    },
  },
];

const checkinColumns = [
  {
    title: '租客姓名',
    dataIndex: 'tenantName',
    key: 'tenantName',
    width: 120,
  },
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 100,
  },
  {
    title: '入住日期',
    dataIndex: 'checkinDate',
    key: 'checkinDate',
    width: 120,
  },
  {
    title: '预计到期',
    dataIndex: 'estimatedExpiry',
    key: 'estimatedExpiry',
    width: 120,
  },
  {
    title: '合同状态',
    dataIndex: 'contractStatus',
    key: 'contractStatus',
    width: 100,
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
  },
];

const historyColumns = [
  {
    title: '租客姓名',
    dataIndex: 'tenantName',
    key: 'tenantName',
    width: 120,
  },
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 100,
  },
  {
    title: '入住日期',
    dataIndex: 'checkinDate',
    key: 'checkinDate',
    width: 120,
  },
  {
    title: '退房日期',
    dataIndex: 'checkoutDate',
    key: 'checkoutDate',
    width: 120,
    customRender: ({ text }: { text: null | string }) => text || '-',
  },
  {
    title: '信用记录',
    dataIndex: 'creditRecord',
    key: 'creditRecord',
    width: 100,
  },
  {
    title: '缴费记录',
    dataIndex: 'paymentRecord',
    key: 'paymentRecord',
    width: 100,
  },
  {
    title: '投诉记录',
    dataIndex: 'complaintRecord',
    key: 'complaintRecord',
    width: 100,
  },
];

// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

const handleContractSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

const addTenant = () => {
  selectedTenant.value = null;
  resetTenantForm();
  tenantModalVisible.value = true;
};

const editTenant = (tenant: any) => {
  selectedTenant.value = tenant;
  Object.assign(tenantForm, tenant);
  tenantModalVisible.value = true;
};

const handleTenantSubmit = async () => {
  try {
    await tenantFormRef.value?.validate();

    if (selectedTenant.value) {
      // 编辑租客
      const index = tenantList.value.findIndex(
        (t) => t.id === selectedTenant.value.id,
      );
      if (index !== -1) {
        tenantList.value[index] = { ...selectedTenant.value, ...tenantForm };
      }
      message.success('租客信息更新成功');
    } else {
      // 新增租客
      const newTenant = {
        id: Date.now(),
        ...tenantForm,
        status: TenantStatus.ACTIVE,
        createTime: new Date().toISOString().split('T')[0],
      };
      tenantList.value.push(newTenant);
      message.success('租客添加成功');
    }

    tenantModalVisible.value = false;
    resetTenantForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleTenantCancel = () => {
  tenantModalVisible.value = false;
  resetTenantForm();
};

const resetTenantForm = () => {
  Object.assign(tenantForm, {
    name: '',
    phone: '',
    idCard: '',
    email: '',
    emergencyContact: '',
    emergencyPhone: '',
    occupation: '',
    workUnit: '',
    annualIncome: '',
    creditScore: 0,
    remark: '',
  });
  tenantFormRef.value?.resetFields();
};

const addContract = () => {
  selectedContract.value = null;
  resetContractForm();
  contractModalVisible.value = true;
};

const editContract = (contract: any) => {
  selectedContract.value = contract;
  Object.assign(contractForm, contract);
  contractModalVisible.value = true;
};

const handleContractSubmit = async () => {
  try {
    await contractFormRef.value?.validate();

    if (selectedContract.value) {
      // 编辑合同
      const index = contractList.value.findIndex(
        (c) => c.id === selectedContract.value.id,
      );
      if (index !== -1) {
        contractList.value[index] = {
          ...selectedContract.value,
          ...contractForm,
        };
      }
      message.success('合同信息更新成功');
    } else {
      // 新增合同
      const tenant = tenantList.value.find(
        (t) => t.id === contractForm.tenantId,
      );
      const newContract = {
        id: Date.now(),
        ...contractForm,
        tenantName: tenant?.name || '',
        status: ContractStatus.ACTIVE,
        createTime: new Date().toISOString().split('T')[0],
      };
      contractList.value.push(newContract);
      message.success('合同添加成功');
    }

    contractModalVisible.value = false;
    resetContractForm();
  } catch (error) {
    console.error('表单验证失败:', error);
  }
};

const handleContractCancel = () => {
  contractModalVisible.value = false;
  resetContractForm();
};

const resetContractForm = () => {
  Object.assign(contractForm, {
    tenantId: '',
    roomNumber: '',
    startDate: null,
    endDate: null,
    rent: 0,
    deposit: 0,
    paymentDay: 1,
    remark: '',
  });
  contractFormRef.value?.resetFields();
};

const viewTenantDetail = (tenant: any) => {
  Modal.info({
    title: `租客详情 - ${tenant.name}`,
    content: `
      <div>
        <p><strong>姓名:</strong> ${tenant.name}</p>
        <p><strong>联系电话:</strong> ${tenant.phone}</p>
        <p><strong>身份证号:</strong> ${tenant.idCard}</p>
        <p><strong>邮箱:</strong> ${tenant.email}</p>
        <p><strong>紧急联系人:</strong> ${tenant.emergencyContact}</p>
        <p><strong>紧急联系电话:</strong> ${tenant.emergencyPhone}</p>
        <p><strong>职业:</strong> ${tenant.occupation}</p>
        <p><strong>工作单位:</strong> ${tenant.workUnit}</p>
        <p><strong>年收入:</strong> ${tenant.annualIncome}</p>
        <p><strong>信用评分:</strong> ${tenant.creditScore}</p>
        <p><strong>备注:</strong> ${tenant.remark}</p>
      </div>
    `,
  });
};

const viewContractDetail = (contract: any) => {
  Modal.info({
    title: `合同详情 - ${contract.tenantName}`,
    content: `
      <div>
        <p><strong>租客姓名:</strong> ${contract.tenantName}</p>
        <p><strong>房间号:</strong> ${contract.roomNumber}</p>
        <p><strong>开始日期:</strong> ${contract.startDate}</p>
        <p><strong>结束日期:</strong> ${contract.endDate}</p>
        <p><strong>月租金:</strong> ¥${contract.rent}</p>
        <p><strong>押金:</strong> ¥${contract.deposit}</p>
        <p><strong>缴费日:</strong> 每月${contract.paymentDay}日</p>
        <p><strong>备注:</strong> ${contract.remark}</p>
      </div>
    `,
  });
};

const deleteTenant = (tenant: any) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除租客"${tenant.name}"吗？`,
    onOk: () => {
      const index = tenantList.value.findIndex((t) => t.id === tenant.id);
      if (index !== -1) {
        tenantList.value.splice(index, 1);
        message.success('租客删除成功');
      }
    },
  });
};

const terminateContract = (contract: any) => {
  Modal.confirm({
    title: '确认终止合同',
    content: `确定要终止"${contract.tenantName}"的合同吗？`,
    onOk: () => {
      const index = contractList.value.findIndex((c) => c.id === contract.id);
      if (index !== -1) {
        contractList.value[index].status = ContractStatus.TERMINATED;
        message.success('合同终止成功');
      }
    },
  });
};

// 生命周期
onMounted(() => {
  // 初始化数据
});
</script>

<template>
  <div class="tenant-management">
    <Card>
      <Tabs v-model:active-key="activeTab">
        <!-- 租客管理 -->
        <Tabs.TabPane key="tenants" tab="租客管理">
          <div class="table-header">
            <Row :gutter="16">
              <Col :span="6">
                <Input
                  v-model:value="searchForm.name"
                  placeholder="租客姓名"
                  allow-clear
                  @change="handleSearch"
                />
              </Col>
              <Col :span="6">
                <Input
                  v-model:value="searchForm.phone"
                  placeholder="联系电话"
                  allow-clear
                  @change="handleSearch"
                />
              </Col>
              <Col :span="6">
                <Input
                  v-model:value="searchForm.roomNumber"
                  placeholder="房间号"
                  allow-clear
                  @change="handleSearch"
                />
              </Col>
              <Col :span="6">
                <Select
                  v-model:value="searchForm.status"
                  placeholder="租客状态"
                  allow-clear
                  @change="handleSearch"
                >
                  <Select.Option value="active">在租</Select.Option>
                  <Select.Option value="inactive">退租</Select.Option>
                  <Select.Option value="expired">到期</Select.Option>
                </Select>
              </Col>
            </Row>
            <div class="table-actions">
              <Button type="primary" @click="addTenant">
                <IconifyIcon icon="ant-design:plus-outlined" />
                新增租客
              </Button>
            </div>
          </div>

          <Table
            :columns="tenantColumns"
            :data-source="filteredTenantList"
            :loading="loading"
            :pagination="false"
            row-key="id"
          />
        </Tabs.TabPane>

        <!-- 合同管理 -->
        <Tabs.TabPane key="contracts" tab="合同管理">
          <div class="table-header">
            <Row :gutter="16">
              <Col :span="6">
                <Input
                  v-model:value="contractSearchForm.name"
                  placeholder="租客姓名"
                  allow-clear
                  @change="handleContractSearch"
                />
              </Col>
              <Col :span="6">
                <Input
                  v-model:value="contractSearchForm.roomNumber"
                  placeholder="房间号"
                  allow-clear
                  @change="handleContractSearch"
                />
              </Col>
              <Col :span="6">
                <Select
                  v-model:value="contractSearchForm.status"
                  placeholder="合同状态"
                  allow-clear
                  @change="handleContractSearch"
                >
                  <Select.Option value="active">生效中</Select.Option>
                  <Select.Option value="expired">已到期</Select.Option>
                  <Select.Option value="terminated">已终止</Select.Option>
                  <Select.Option value="pending">待生效</Select.Option>
                </Select>
              </Col>
            </Row>
            <div class="table-actions">
              <Button type="primary" @click="addContract">
                <IconifyIcon icon="ant-design:plus-outlined" />
                新增合同
              </Button>
            </div>
          </div>

          <Table
            :columns="contractColumns"
            :data-source="filteredContractList"
            :loading="loading"
            :pagination="false"
            row-key="id"
          />
        </Tabs.TabPane>

        <!-- 入住记录 -->
        <Tabs.TabPane key="checkin" tab="入住记录">
          <Card title="入住记录">
            <Table
              :columns="checkinColumns"
              :data-source="checkinRecords"
              :loading="loading"
              :pagination="false"
              row-key="id"
            />
          </Card>
        </Tabs.TabPane>

        <!-- 历史档案 -->
        <Tabs.TabPane key="history" tab="历史档案">
          <Card title="历史档案">
            <Table
              :columns="historyColumns"
              :data-source="tenantHistory"
              :loading="loading"
              :pagination="false"
              row-key="id"
            />
          </Card>
        </Tabs.TabPane>
      </Tabs>
    </Card>

    <!-- 租客信息模态框 -->
    <Modal
      v-model:open="tenantModalVisible"
      :title="selectedTenant ? '编辑租客' : '新增租客'"
      width="800px"
      @ok="handleTenantSubmit"
      @cancel="handleTenantCancel"
    >
      <Form
        ref="tenantFormRef"
        :model="tenantForm"
        :rules="tenantRules"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <Form.Item label="姓名" name="name">
              <Input
                v-model:value="tenantForm.name"
                placeholder="请输入租客姓名"
              />
            </Form.Item>
          </Col>
          <Col :span="12">
            <Form.Item label="联系电话" name="phone">
              <Input
                v-model:value="tenantForm.phone"
                placeholder="请输入联系电话"
              />
            </Form.Item>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <Form.Item label="身份证号" name="idCard">
              <Input
                v-model:value="tenantForm.idCard"
                placeholder="请输入身份证号"
              />
            </Form.Item>
          </Col>
          <Col :span="12">
            <Form.Item label="邮箱" name="email">
              <Input
                v-model:value="tenantForm.email"
                placeholder="请输入邮箱"
              />
            </Form.Item>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <Form.Item label="紧急联系人" name="emergencyContact">
              <Input
                v-model:value="tenantForm.emergencyContact"
                placeholder="请输入紧急联系人"
              />
            </Form.Item>
          </Col>
          <Col :span="12">
            <Form.Item label="紧急联系电话" name="emergencyPhone">
              <Input
                v-model:value="tenantForm.emergencyPhone"
                placeholder="请输入紧急联系电话"
              />
            </Form.Item>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <Form.Item label="职业" name="occupation">
              <Input
                v-model:value="tenantForm.occupation"
                placeholder="请输入职业"
              />
            </Form.Item>
          </Col>
          <Col :span="12">
            <Form.Item label="工作单位" name="workUnit">
              <Input
                v-model:value="tenantForm.workUnit"
                placeholder="请输入工作单位"
              />
            </Form.Item>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <Form.Item label="年收入" name="annualIncome">
              <Input
                v-model:value="tenantForm.annualIncome"
                placeholder="请输入年收入"
              />
            </Form.Item>
          </Col>
          <Col :span="12">
            <Form.Item label="信用评分" name="creditScore">
              <InputNumber
                v-model:value="tenantForm.creditScore"
                :min="0"
                :max="100"
                placeholder="请输入信用评分"
              />
            </Form.Item>
          </Col>
        </Row>
        <Form.Item label="备注" name="remark">
          <Input.TextArea
            v-model:value="tenantForm.remark"
            placeholder="请输入备注信息"
          />
        </Form.Item>
      </Form>
    </Modal>

    <!-- 合同信息模态框 -->
    <Modal
      v-model:open="contractModalVisible"
      :title="selectedContract ? '编辑合同' : '新增合同'"
      width="800px"
      @ok="handleContractSubmit"
      @cancel="handleContractCancel"
    >
      <Form
        ref="contractFormRef"
        :model="contractForm"
        :rules="contractRules"
        layout="vertical"
      >
        <Row :gutter="16">
          <Col :span="12">
            <Form.Item label="租客" name="tenantId">
              <Select
                v-model:value="contractForm.tenantId"
                placeholder="请选择租客"
              >
                <Select.Option
                  v-for="tenant in tenantList"
                  :key="tenant.id"
                  :value="tenant.id"
                >
                  {{ tenant.name }} - {{ tenant.phone }}
                </Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col :span="12">
            <Form.Item label="房间号" name="roomNumber">
              <Input
                v-model:value="contractForm.roomNumber"
                placeholder="请输入房间号"
              />
            </Form.Item>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <Form.Item label="开始日期" name="startDate">
              <DatePicker
                v-model:value="contractForm.startDate"
                placeholder="请选择开始日期"
                style="width: 100%"
              />
            </Form.Item>
          </Col>
          <Col :span="12">
            <Form.Item label="结束日期" name="endDate">
              <DatePicker
                v-model:value="contractForm.endDate"
                placeholder="请选择结束日期"
                style="width: 100%"
              />
            </Form.Item>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="8">
            <Form.Item label="月租金" name="rent">
              <InputNumber
                v-model:value="contractForm.rent"
                :min="0"
                placeholder="请输入月租金"
                style="width: 100%"
              />
            </Form.Item>
          </Col>
          <Col :span="8">
            <Form.Item label="押金" name="deposit">
              <InputNumber
                v-model:value="contractForm.deposit"
                :min="0"
                placeholder="请输入押金"
                style="width: 100%"
              />
            </Form.Item>
          </Col>
          <Col :span="8">
            <Form.Item label="每月缴费日" name="paymentDay">
              <InputNumber
                v-model:value="contractForm.paymentDay"
                :min="1"
                :max="31"
                placeholder="缴费日"
                style="width: 100%"
              />
            </Form.Item>
          </Col>
        </Row>
        <Form.Item label="备注" name="remark">
          <Input.TextArea
            v-model:value="contractForm.remark"
            placeholder="请输入备注信息"
          />
        </Form.Item>
      </Form>
    </Modal>
  </div>
</template>

<style scoped>
.tenant-management {
  padding: 16px;
}

.table-header {
  margin-bottom: 16px;
}

.table-actions {
  margin-top: 16px;
  text-align: right;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background-color: #fafafa;
}

:deep(.ant-tabs-tab) {
  font-size: 14px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}
</style>
